package team.nmsg.ge.system.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import team.nmsg.ge.system.bean.PageObject;
import team.nmsg.ge.system.bean.PublishThreadInfo;
import team.nmsg.ge.system.bean.SysBusinessLog;
import team.nmsg.ge.system.bean.SysOper;
import team.nmsg.ge.system.bean.SysRole;
import team.nmsg.ge.system.bean.SysUser;
import team.nmsg.ge.system.init.CommonDefine;
import team.nmsg.ge.system.init.shiro.SysAuthorizingRealm;
import team.nmsg.ge.system.service.ISystemLogService;
import team.nmsg.ge.system.service.IUserRoleService;
import team.nmsg.ge.system.util.MD5Encrypt;
import team.nmsg.ge.system.util.SysLanguageHelper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("sys")
public class SystemController extends BaseController {

	private static Logger logger = LoggerFactory
			.getLogger(SystemController.class);

	@Autowired
	IUserRoleService userRoleService = null;

	@Autowired
	ISystemLogService systemLogService = null;

	@RequestMapping("/userManage")
	public String userHome() {

		return "system/UserFrame";
	}

	@RequestMapping("/QueryUser")
	public String QueryUser(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();

		String pageSize = req.getParameter("pageSize");
		String currentPage = req.getParameter("currentPage");
		int startIndex = 0;
		startIndex = Integer.parseInt(pageSize)
				* (Integer.parseInt(currentPage) - 1);

		SysUser user = new SysUser();

		PageObject<SysUser> page = userRoleService.QueryUser(
				Integer.parseInt(pageSize), startIndex, user);
		JSONArray arr = new JSONArray();
		for (SysUser u : page.getCurrentEntitys()) {
			arr.add(u.toJson());
		}
		obj.put("data", arr);
		obj.put("total", page.getSumCount());

		writeJson(obj, resp);
		return null;
	}

	@RequestMapping("/logs")
	public ModelAndView systemLog(HttpServletRequest req,
			HttpServletResponse resp) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<Integer, String> logTypes = CommonDefine.logTypeToDesc;
		data.put("logTypes", logTypes);
		ModelAndView mv = new ModelAndView("system/SystemLog", data);
		return mv;
	}

	@RequestMapping("/queryLogs")
	public String queryLogs(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		String pageSize = req.getParameter("pageSize");
		String currentPage = req.getParameter("currentPage");
		int startIndex = 0;
		startIndex = Integer.parseInt(pageSize)
				* (Integer.parseInt(currentPage) - 1);
		String username = getParaByConvert("username", req);
		String startTime = req.getParameter("startTime");
		String endTime = req.getParameter("endTime");
		long _startTime = 0;
		long _endTime = 0;
		if (!"NaN".equals(startTime)) {
			_startTime = Long.valueOf(startTime);
		}
		if (!"NaN".equals(endTime)) {
			_endTime = Long.valueOf(endTime);
		}

		String logType = req.getParameter("logType");

		SysBusinessLog logBean = new SysBusinessLog();
		logBean.setOperUserName(username);
		logBean.setOperKey(logType);
		PageObject<SysBusinessLog> page = systemLogService.queryLogs(
				Integer.parseInt(pageSize), startIndex, logBean, _startTime,
				_endTime);

		JSONArray arr = new JSONArray();
		for (SysBusinessLog log : page.getCurrentEntitys()) {
			String operDesc = log.getOperDesc();
			String operArgs = log.getOperArgs();
			Object[] array = null;
			if (!StringUtils.isEmpty(operArgs)) {
				JSONArray fromObject = JSONObject.parseArray(operArgs);
				array = fromObject.toArray();
			}
			String msg = SysLanguageHelper.getMsg(operDesc, array, req);
			log.setOperDesc(msg);
			String operKey = log.getOperKey();
			String string = CommonDefine.logTypeToDesc.get(Integer
					.parseInt(operKey));
			JSONObject json = log.toJson();
			json.put("logType", string);
			arr.add(json);
		}

		obj.put("data", arr);
		obj.put("total", page.getSumCount());

		writeJson(obj, resp);
		return null;

	}

	@RequiresPermissions("DelSysLog")
	@RequestMapping("/deleteLogByID")
	public String deleteLogByID(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		String logIdJson = req.getParameter("logId");
		JSONArray logIdArr = JSONArray.parseArray(logIdJson);
		List<String> logIds = new ArrayList<String>();
		for (int i = 0; i < logIdArr.size(); i++) {
			logIds.add(logIdArr.getString(i));
		}
		try {
			boolean result = systemLogService.deleteLogById(logIds);
			obj.put("result", result);
		} catch (Exception e) {
			logger.error(" SystemControllerExceptionHandler ::: ", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequestMapping("/findAllRoles")
	public String findAllRoles(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {

			List<SysRole> findAllRoles = userRoleService.findAllRoles();

			JSONArray arr = new JSONArray();
			for (SysRole r : findAllRoles) {
				arr.add(r.toJson());
			}

			obj.put("result", arr);
			obj.put("aaData", arr);
		} catch (Exception e) {
			obj.put("result", null);
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequiresPermissions("AddUser")
	@RequestMapping("/addSysUser")
	public String addSysUser(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			String user = req.getParameter("user");
			JSONObject userObj = JSONObject.parseObject(user);
			String uname = userObj.getString("username");
			String upass = userObj.getString("password");
			String phone = userObj.getString("phone");
			String email = userObj.getString("email");
			JSONArray roleids = userObj.getJSONArray("roles");
			Set<SysRole> roles = new HashSet<SysRole>();
			SysUser sysUser = new SysUser();
			if (roleids != null) {
				for (Object id : roleids) {
					SysRole nmsRole = new SysRole();
					nmsRole.setRoleId(Integer.parseInt(id.toString()));
					roles.add(nmsRole);
				}
				sysUser.setRoles(roles);
			} else {
				sysUser.setRoles(null);
			}
			sysUser.setUsername(uname);
			sysUser.setPassword(MD5Encrypt.getMD5Str(upass));
			sysUser.setUserRemark("");
			long nowTime = System.currentTimeMillis();
			sysUser.setCreateTimestamp(nowTime);
			sysUser.setLastUpdateTimestamp(nowTime);
			sysUser.setUserStatus(SysUser.USER_STATUS_NORMAL);
			sysUser.setLoginCounter(0l);
			sysUser.setPhoneNo(phone);
			sysUser.setEmail(email);
			sysUser = userRoleService.addSysUser(sysUser);
			if (sysUser != null && sysUser.getUserId() != null) {
				obj.put("result", true);
			}
		} catch (Exception e) {
			obj.put("result", false);
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequiresPermissions("DelUser")
	@RequestMapping("/DeleteUserByID")
	public void DeleteUserByID(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		String userIds = req.getParameter("userIds");
		JSONArray UserIds = JSONArray.parseArray(userIds);
		boolean flag = false;
		String[] userIdArr = new String[UserIds.size()];
		for (int i = 0; i < userIdArr.length; i++) {
			String id = UserIds.getString(i);
			if (id.equals("1")) {
				flag = true;
				break;
			}
			userIdArr[i] = id;
		}
		if (flag) {
			obj.put("result", false);
		} else {
			userRoleService.deleteUserByID(userIdArr);
			obj.put("result", true);
		}
		writeJson(obj, resp);

	}

	@RequestMapping("/findAllRoles_userRole")
	public String queryUserRole(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {

			List<SysRole> findAllRoles = userRoleService.findAllRoles();
			JSONArray arr = new JSONArray();
			for (SysRole r : findAllRoles) {
				arr.add(r.toJson());
			}
			obj.put("result", arr); // 所有角色

			String userid = req.getParameter("uid");
			SysUser sysUser = new SysUser();
			sysUser = userRoleService.queryUserById(Integer.parseInt(userid));
			JSONArray arr2 = new JSONArray();
			JSONArray roleIds = new JSONArray();
			for (SysRole role : sysUser.getRoles()) {
				arr2.add(role.toJson());
				roleIds.add(role.getRoleId());
			}
			obj.put("userInfo", sysUser.toJson());
			obj.put("result2", arr2); // 该用户所拥有的角色
			obj.put("roleIds", roleIds);
		} catch (Exception e) {
			obj.put("result", null);
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;

	}

	@RequiresPermissions("UpdUser")
	@RequestMapping("/updataUser")
	public void updataUser(HttpServletRequest req, HttpServletResponse resp) {

		String userStr = req.getParameter("user");
		JSONObject userObj = JSONObject.parseObject(userStr);

		String upass = userObj.getString("password");
		String uStatus = userObj.getString("sysUserStatus");
		String uRemark = userObj.getString("userRemark");
		String uPhone = userObj.getString("phone");
		String uEmail = userObj.getString("email");
		String uid = userObj.getString("userId");
		String username = userObj.getString("username");
		JSONArray roleids = userObj.getJSONArray("roleIds");
		Set<SysRole> roles = new HashSet<SysRole>();
		SysUser sysUser = new SysUser();
		if (roleids != null) {
			for (Object id : roleids) {
				SysRole sysRole = new SysRole();
				sysRole.setRoleId(Integer.parseInt(id.toString()));
				roles.add(sysRole);
			}
			sysUser.setRoles(roles);
		} else {
			sysUser.setRoles(null);
		}

		if (!upass.equals("")) {
			sysUser.setPassword(MD5Encrypt.getMD5Str(upass));
		}
		sysUser.setUserStatus(Integer.parseInt(uStatus));
		sysUser.setUserRemark(uRemark);
		sysUser.setPhoneNo(uPhone);
		sysUser.setEmail(uEmail);
		sysUser.setUserId(Integer.parseInt(uid));
		sysUser.setUsername(username);

		userRoleService.updUser(sysUser);

		JSONObject obj = new JSONObject();
		obj.put("result", 1);

		writeJson(obj, resp);
	}

	@RequestMapping("/roleManage")
	public String roleManage() {

		return "system/RoleFrame";
	}

	@RequestMapping("/findAllOpers")
	public String findAllOpers(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		String operId, operName, nmsPoId;
		try {
			JSONArray arr = new JSONArray();
			List<SysOper> findAllOpers = userRoleService.findAllOpers();
			for (SysOper p : findAllOpers) {
				JSONObject ob = new JSONObject();
				operId = p.toJson().getString("operId");
				operName = p.toJson().getString("operName");
				nmsPoId = p.toJson().getString("sysPoId");
				ob.put("id", operId);
				ob.put("text", operName);
				if (Integer.valueOf(nmsPoId) == -1) {
					ob.put("parent", "#");
				} else {
					ob.put("parent", nmsPoId);
				}
				arr.add(ob);
			}
			obj.put("result", arr);
		} catch (Exception e) {
			obj.put("result", null);
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequestMapping("/findAuthByRole")
	public String findAuthByRole(HttpServletRequest req,
			HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			JSONArray arr = new JSONArray();
			String rid = req.getParameter("rid");
			Set<SysOper> findAuthByRole = userRoleService.getAuthByRole(rid);
			for (SysOper r : findAuthByRole) {
				arr.add(r.getOperId());
			}

			obj.put("result", arr);
		} catch (Exception e) {
			obj.put("result", null);
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;

	}

	@RequiresPermissions("AddRole")
	@RequestMapping("/addsysRole")
	public String addsysRole(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			JSONArray arr = new JSONArray();
			String rolename = req.getParameter("rolename");
			String roleremark = req.getParameter("roleremark");
			SysRole sysRole = new SysRole();
			sysRole.setRoleName(rolename);
			sysRole.setRoleRemark(roleremark);
			sysRole.setCreateTimestamp(System.currentTimeMillis());

			sysRole = userRoleService.addSysRole(sysRole);

			if (sysRole != null) {
				arr.add(sysRole.toJson());
				obj.put("result", arr);
			}
		} catch (Exception e) {
			obj.put("result", false);
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequiresPermissions("DelRole")
	@RequestMapping("/deletesysRole")
	public String deleteSysRole(HttpServletRequest req, HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			// String rootId = NMSUserRoleParser.admins.getRoleId().toString();
			String rid = req.getParameter("rid");
			// String rname=req.getParameter("rname");
			if (!"1".equals(rid)) {
				boolean deletenmsrole = userRoleService.delSysRole(rid);
				obj.put("result", deletenmsrole);
			} else {
				obj.put("result", "isAdmin");
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequiresPermissions("DelRole")
	@RequestMapping("/batchDelsysRole")
	public String batchDelsysRole(HttpServletRequest req,
			HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			// String rootId = NMSUserRoleParser.admins.getRoleId().toString();
			String rid = req.getParameter("rid");
			JSONArray arr = JSONArray.parseArray(rid);
			for (int i = 0; i < arr.size(); i++) {
				String id = arr.getString(i);
				if (!"1".equals(id)) {
					boolean deletenmsrole = userRoleService.delSysRole(id);
					obj.put("result", deletenmsrole);
				} else {
					obj.put("result", "isAdmin");
				}
			}

		} catch (Exception e) {
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequiresPermissions("GrantOperToRole")
	@RequestMapping("/updGrantOperToRole")
	public String updGrantOperToRole(HttpServletRequest req,
			HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			String rname = req.getParameter("rname");
			int rid = Integer.valueOf(req.getParameter("roleId"));
			String[] operspath = req.getParameterValues("opers[]");// 权限节点路径
			String[] operId;// 权限id
			String[] operIds = null;// 权限id集合
			List<String> list = new ArrayList<String>();
			if (operspath != null) {// 获取路径上的权限
				for (int i = 0; i < operspath.length; i++) {
					operId = operspath[i].split("/");
					for (int j = 0; j < operId.length; j++) {
						if (!list.contains(operId[j])) { // 去除重复父节点
							list.add(operId[j]);
						}
					}
				}
				operIds = list.toArray(new String[1]);
			}

			userRoleService.updModifyOperToRole(rid, operIds, rname);
			obj.put("result", true);
		} catch (Exception e) {
			obj.put("result", null);
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;

	}

	@RequiresPermissions("GrantOperToRole")
	@RequestMapping("/grantOperToRole")
	public String grantOperToRole(HttpServletRequest req,
			HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			String rname = req.getParameter("rname");
			int rid = Integer.valueOf(req.getParameter("roleId"));
			String opers = req.getParameter("opers");// 权限节点路径
			JSONArray arr = JSONArray.parseArray(opers);
			String[] operIds = null;// 权限id集合
			List<String> list = new ArrayList<String>();
			int size = arr.size();
			if (size > 0) {
				for (int i = 0; i < size; i++) {
					String operId = arr.getString(i);
					list.add(operId);
				}
				operIds = list.toArray(new String[1]);
			}
			userRoleService.updModifyOperToRole(rid, operIds, rname);
			obj.put("result", true);
		} catch (Exception e) {
			obj.put("result", null);
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;

	}

	// @RequestMapping("/changePassword")
	// public String changePassword(HttpServletRequest req, HttpServletResponse
	// resp) {
	// JSONObject obj = new JSONObject();
	// try {
	// SysUser user = (SysUser)SysAuthorizingRealm.getShiroSessionAttr("user");
	// String oldPassword = req.getParameter("oldPassword");
	// String newPassword = req.getParameter("newPassword");
	// boolean changePassword=userRoleService.updChangePassword(user,
	// oldPassword, newPassword);
	// obj.put("result", changePassword);
	// }catch (Exception e) {
	// logger.error("", e);
	// }
	// writeJson(obj, resp);
	// return null;
	// }
	//
	// @RequestMapping("/getPublishThread")
	// public String getPublishThread(HttpServletRequest req,
	// HttpServletResponse resp) {
	// JSONObject obj = new JSONObject();
	// try {
	// for (String key : CommonDefine.TypeToPublishThread.keySet()) {
	// Map<String,PublishThreadInfo> thread =
	// CommonDefine.TypeToPublishThread.get(key);
	// JSONArray array = new JSONArray();
	// for (String k : thread.keySet()) {
	// array.add(thread.get(k).toJson());
	// }
	// obj.put(key, array);
	// }
	//
	// JSONArray allClientInfo = userRoleService.getAllClientInfo();
	// obj.put("onlineUsers", allClientInfo);
	//
	// obj.put("isAuthPublish" , systemLogService.isAuthPublish());
	//
	// obj.put("isAuthDownload", systemLogService.isAuthDownload());
	//
	// }catch (Exception e) {
	// logger.error("", e);
	// }
	// writeJson(obj, resp);
	// return null;
	// }

	@RequestMapping("/monitor")
	public String monitor() {

		return "system/MonitorFrame";
	}

	@RequestMapping("/setPublish_key")
	public String setPublish_key(HttpServletRequest req,
			HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			String status = req.getParameter("status");
			int setPublish_value = systemLogService.setPublish_value(status);
			obj.put("result", setPublish_value == 1 ? true : false);

		} catch (Exception e) {
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequestMapping("/setDownload_key")
	public String setDownload_key(HttpServletRequest req,
			HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		try {
			String status = "";
			status = req.getParameter("status");

			// JSONObject is = getStringFromStream(req);
			// status = is.getString("status");

			int setDownload_value = systemLogService.setDownload_key(status);
			obj.put("result", setDownload_value == 1 ? true : false);

		} catch (Exception e) {
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	private JSONObject getStringFromStream(HttpServletRequest req) {
		ServletInputStream is;
		try {
			is = req.getInputStream();
			int nRead = 1;
			int nTotalRead = 0;
			byte[] bytes = new byte[10240];
			while (nRead > 0) {
				nRead = is.read(bytes, nTotalRead, bytes.length - nTotalRead);
				if (nRead > 0)
					nTotalRead = nTotalRead + nRead;
			}
			String str = new String(bytes, 0, nTotalRead, "utf-8");
			return JSONObject.parseObject(str);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	@RequestMapping("/getPortImgList")
	public String getPortImgList(HttpServletRequest req,
			HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		JSONArray imgList = new JSONArray();
		try {
			File file1 = new File(System.getProperty("user.dir")
					+ "/resources/images/port");
			// 把文件里面内容放进数组
			File[] fs = file1.listFiles();
			for (File f : fs) {
				if (f.isFile()) {
					JSONObject tmpObj = new JSONObject();
					tmpObj.put("name", f.getName());
					tmpObj.put("path", "/resources/images/port/" + f.getName());
					imgList.add(tmpObj);
				}
			}
			obj.put("imgList", imgList);
		} catch (Exception e) {
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}

	@RequestMapping("/getPowerImgList")
	public String getPowerImgList(HttpServletRequest req,
			HttpServletResponse resp) {
		JSONObject obj = new JSONObject();
		JSONArray imgList = new JSONArray();
		try {
			File file1 = new File(System.getProperty("user.dir")
					+ "/resources/images/power");
			// 把文件里面内容放进数组
			File[] fs = file1.listFiles();
			for (File f : fs) {
				if (f.isFile()) {
					JSONObject tmpObj = new JSONObject();
					tmpObj.put("name", f.getName());
					tmpObj.put("path", "/resources/images/power/" + f.getName());
					imgList.add(tmpObj);
				}
			}
			obj.put("imgList", imgList);
		} catch (Exception e) {
			logger.error("", e);
		}
		writeJson(obj, resp);
		return null;
	}
	
	/**   
     * 文件上传具体实现方法;   
     *    
     * @param file   
     * @return   
     */    
    @RequestMapping("/uploadImg")    
    public String handleFileUpload(HttpServletRequest request,HttpServletResponse response,@RequestParam("file") MultipartFile file) {    
    	String type = request.getParameter("type");
    	JSONObject obj = new JSONObject();
    	if (!file.isEmpty()) {    
            try {    
                String contextpath =System.getProperty("user.dir")
    					+ "/resources/images/"+type;
                File f = new File(contextpath); 
                if(!f.exists()){
                    f.mkdirs();
                }
                String filename = file.getOriginalFilename();
                String filepath = contextpath+"/"+filename;
                file.transferTo(new File(filepath));  
            } catch (FileNotFoundException e) {    
                e.printStackTrace();    
                return  "false";    
            } catch (IOException e) {    
                e.printStackTrace();    
                return "false";    
            }    
            writeJson(obj, response);
            return null;
        } else {    
            return "false";    
        }    
    }    

 

}
